﻿using MathNet.Numerics.Distributions;
using Microsoft.AspNetCore.Mvc;
using ztDataNet.Db;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using SqlSugar;
using StackExchange.Redis;
using K4os.Compression.LZ4.Internal;
using System.Data;

namespace ztDataNet.Controllers
{
    /// <summary>
    /// 功法登记
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class MemosController : BaseController<memos>
    {

        private readonly ISqlSugarClient db;
        /// <summary>
        /// 徒弟修为控制器
        /// </summary>
        /// <param name="db"></param>
        /// <param name="cc"></param>
        public MemosController(ISqlSugarClient db, IDistributedCache cc) : base(db, cc)
        {
            this.db = db;
        }
        /// <summary>
        /// 按日期查询
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        [HttpGet("GetMemoByDate")]
        public async Task<IActionResult> GetMemoByDate(string d)
        {
            var data = db.Queryable<memos>().Where(x=>x.inputtime ==DateTime.Parse(d)).ToList();
            var memoWithRemindersList = new List<MemoWithReminders>();

            foreach (memos m in data)
            {
                
                var reminders = new List<reminders>(); // 填充 Reminder 对象列表

                // 解析 times 字段，填充 reminders 列表
                reminders = db.Queryable<reminders>().Where(x=>x.memo_id == m.id).ToList();
                
                memoWithRemindersList.Add(new MemoWithReminders
                {
                    m = m,
                    r = reminders
                });
            }
            return Ok(memoWithRemindersList);
        }


        /// <summary>
        /// 事务插入
        /// </summary>

        /// <returns></returns>
        /// 
        [HttpPost("InsterMemo")]
        public async Task<IActionResult> InsterMemo([FromBody] MemoWithReminders w)
        {


            Serilog.Log.Information($"MemoWithReminders INFO: {w}");
            try
                {
                    db.Ado.BeginTran();
                    var memoId = db.Insertable(w.m).ExecuteReturnIdentity();
                foreach (var reminder in w.r)
                {
                    reminder.memo_id = memoId;
                    db.Insertable(reminder).ExecuteCommand();
                }
                db.Ado.CommitTran();
                }
                catch (Exception ex)
                {
                    db.Ado.RollbackTran();
                Serilog.Log.Information($"MemoWithReminders ERROR: {ex.Message}");
                return BadRequest("An error occurred while adding entities");
            }
            
            return Ok("ok");
        }

    }
    public class MemoWithReminders
    {
        public memos m { get; set; }
        public List<reminders> r { get; set; }
    }
}
